package com.example.demo.config;

import com.example.demo.common.AjaxResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;

/**
 * @Author：徐志荣
 * @Date：2023/6/26 上午 10:08
 */

/*
* 实现数据统一返回的保底类
* 说明:在返回数据之前,检测数据的类型是否是统一的对象,如果不是,封装成统一的对象
* */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

   @Resource
    private ObjectMapper objectMapper;
    /*
    * 开关,如果true 才会调用 beforeBodyWrite
    * 基本上都是 一个true
    * */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    /*
    * 对数据格式进行校验 和 封装
    * */

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof AjaxResult){
            return body;
        }
        if(body instanceof String){
            //把 body 首先,封装成统一的对象,再 手动的转换成JSON
            return objectMapper.writeValueAsString(AjaxResult.success(body));
        }
        return AjaxResult.success(body);
    }
}
